package controller

import (
	"net/url"
	"os"

	"github.com/gin-gonic/gin"
	"khao.fun/shizhan/model"
	"khao.fun/shizhan/response"
	"khao.fun/shizhan/service"
)

// @Summary 下载单个文件
// @Description 下载单个文件
// @Tags download
// @Produce json
// @Param fId query string true "下载文件的id"
// @Success 200 {string} string "{"msg": "请求成功","文件可能已被删除"}"
// @Failure 400 {string} string "{"msg": "获取文件id时错误"}"
// @Failuer 404 {string} string "{"msg": "文件不存在"}"
// @Router /download/file [get]
func DownloadFile(ctx *gin.Context) {
	fileId := ctx.Query("fId")
	if fileId == "" {
		response.Fail(ctx, 400, nil, "获取文件id时错误")
		return
	}
	fileInfo := &model.File{}
	err := service.FileInfo(fileInfo, fileId)
	if err != nil || fileInfo.Id == 0 {
		response.Fail(ctx, 404, nil, "文件不存在")
		return
	}
	fileDir := fileInfo.FilePath
	fileName := fileInfo.Filename
	//打开文件
	_, errByOpenFile := os.Open(fileDir)
	//非空处理
	if errByOpenFile != nil {
		response.Success(ctx, errByOpenFile, "文件可能已被删除")
		return
	}
	ctx.Header("Content-Type", "application/octet-stream;charset=utf-8")
	ctx.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(fileName)) //filename=用于给文件命名，url.QueryEscape()用于处理中文乱码，但处理后仍然不是中文
	ctx.Header("Content-Transfer-Encoding", "binary")
	ctx.File(fileDir)
	response.Success(ctx, nil, "请求成功")
}

// @Summary 下载单个图片
// @Description 下载单个图片
// @Tags download
// @Produce json
// @Param imgId query string true "下载图片的id"
// @Success 200 {string} string "{"msg": "请求成功","图片可能已被删除"}"
// @Failure 400 {string} string "{"msg": "获取图片id时错误"}"
// @Failuer 404 {string} string "{"msg": "图片不存在"}"
// @Router /download/image [get]
func DownloadImage(ctx *gin.Context) {
	fileId := ctx.Query("imgId")
	if fileId == "" {
		response.Fail(ctx, 400, nil, "获取图片id时错误")
		return
	}
	fileInfo := &model.Image{}
	err := service.ImageInfo(fileInfo, fileId)
	if err != nil || fileInfo.Id == 0 {
		response.Fail(ctx, 404, nil, "文件不存在")
		return
	}
	fileDir := fileInfo.ImagePath
	fileName := ""
	for i := len(fileDir) - 1; i >= 0; i-- {
		if fileDir[i] == '/' {
			fileName = fileDir[i+1:]
			break
		}
	}
	//打开文件
	_, errByOpenFile := os.Open(fileDir)
	//非空处理
	if errByOpenFile != nil {
		response.Success(ctx, errByOpenFile, "图片可能已被删除")
		return
	}
	ctx.Header("Content-Type", "application/octet-stream;charset=utf-8")
	ctx.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(fileName))
	ctx.Header("Content-Transfer-Encoding", "binary")
	ctx.File(fileDir)
	response.Success(ctx, nil, "请求成功")
}
